<!--
 * @Author       : xiaowu wwl093000@163.com
 * @Date         : 2023-06-26 15:23:25
 * @LastEditTime : 2023-07-05 10:40:12
 * @LastEditors  : xiaowu wwl093000@163.com
 * @FilePath     : /erp-admin-ui/src/components/PictureEditor/index.vue
 * @Description  : -
-->
<template>
  <div className="picture-editor-component">
    <iframe id="editor-Iframe" src="" frameBorder="no" scrolling="no"/>
  </div>
</template>

<script>
export default {
  name: 'PictureEditor',
  props: {
    data: {
      type: Object,
      required: true
    },
    onChange: {
      type: Function,
      required: false
    },
    onCompleted: {
      type: Function,
      required: true
    },
  },
  data() {
    return {
      dateSrc: "https://www.alifanyi.com/erp/imageTrans.html?t=" + new Date().getTime()
    }
  },
  methods: {
    receiveMessage(event) {
      if (event.data && !event.data.type) {
        const postData = JSON.parse(event.data);
        const {type, data} = postData;
        console.log('postData', postData)
        switch (type) {
          case 'base64':
            this.onCompleted(data);
            return false;
          case 'psd':
            this.onChange(data);
            return false;
          case 'autoHeight':
            const iframe = document.getElementById('editor-Iframe');
            iframe.style.height = data.editorHeight + 'px';
            return false;
          default:
            return false;
        }
      }
    },
    postMessage() {
      const iFrame = document.getElementById('editor-Iframe');
      iFrame.src = this.dateSrc
      console.log('iFrame', iFrame)
      const {sourceLang, targetLang, templateJson} = this.data;
      if (iFrame) {
        iFrame.onload = function () {
          let data = {
            sourceLang,
            targetLang,
            templateJson,
            locale: 'zh-cn', // zh-cn 或者 en 或者 ko，新版编辑器的界面语种。默认值为zh-cn
            // downloadable: true, // 默认为true, 如果是false的时候，则不会显示 下载图片 按钮，仅新版本生效
            // submitText: '完成编辑', // 提交按钮的文案，默认根据语种切换
            // downloadText: '下载图片', // 下载按钮的文案，默认根据语种切换
          };
          iFrame.contentWindow.postMessage(JSON.stringify(data), '*');
        };
      }
    },
    init(e) {
      console.log('eeeee', e)
      if (e != '1') {
        window.addEventListener('message', this.receiveMessage, true);
      }
      this.postMessage();
    },
    // remove(){
    //   console.log("remove")
    //   window.removeEventListener("message", this.receiveMessage)
    // }
  },
  created() {
    console.log("created")
  },
  mounted() {
    console.log("mounted")
  },
}
</script>
<style scoped>
.picture-editor-component {
  width: 1440px;
  margin: 0 auto;
  margin-bottom: 20px;
}

iframe {
  width: 1440px;
}
</style>
